<template>
  <div class="counselor-detail">
    <div class="header">
      <el-icon class="back-icon" @click="router.back()">
        <ArrowLeft />
      </el-icon>
      <span class="title">咨询师详情</span>
    </div>

    <div class="content">
      <!-- 基本信息卡片 -->
      <div class="info-card">
        <div class="avatar-container">
          <img
            :src="counselorInfo.avatar ? (counselorInfo.avatar.startsWith('http') ? counselorInfo.avatar : base.baseUrl + counselorInfo.avatar) : ''"
            class="avatar"
            alt="咨询师头像"
          />
        </div>
        <div class="info-content">
          <h2 class="name">{{ counselorInfo.name }}</h2>
          <p class="introduction">{{ counselorInfo.introduction || '暂无个人介绍' }}</p>
        </div>
      </div>

      <!-- 空闲时间卡片 -->
      <div class="free-time-card">
        <h3 class="card-title">可预约时间</h3>
        <div class="free-time-list">
          <div v-if="filteredFreeTimeList.length === 0" class="no-data">
            暂无可预约时间
          </div>
          <div v-else v-for="(item, index) in filteredFreeTimeList" :key="index" class="time-item">
            <div class="date">{{ item.date }}</div>
            <div class="time-slots">
              <el-tag
                v-for="(slot, slotIndex) in item.time_slots"
                :key="slotIndex"
                class="time-slot"
                type="success"
              >
                {{ slot }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { Api } from '@/api'
import base from '@/api/base.js'

const router = useRouter()
const route = useRoute()
const counselorInfo = ref({})
const freeTimeList = ref([])

// 获取咨询师基本信息
const getCounselorInfo = async () => {
  try {
    const response = await Api.getUserById({
      id: route.params.id
    })
    if (response.data.status === 200) {
      counselorInfo.value = response.data.data
    } else {
      throw new Error(response.data.message || '获取咨询师信息失败')
    }
  } catch (error) {
    console.error('获取咨询师信息失败:', error)
    ElMessage.error(error.message || '获取咨询师信息失败，请稍后再试')
  }
}

// 获取咨询师可预约时间
const getCounselorFreeTime = async () => {
  try {
    const res = await Api.getCounselorFreeTime({
      counselor_id: route.params.id
    })
    if (res.data.status === 200 && Array.isArray(res.data.data)) {
      freeTimeList.value = res.data.data
    } else {
      freeTimeList.value = []
    }
  } catch (error) {
    console.error('获取可预约时间失败:', error)
    freeTimeList.value = []
  }
}

// 只显示今天及以后的可预约时间
const filteredFreeTimeList = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  // 先过滤掉过期的
  const validList = freeTimeList.value
    .filter(item => {
      const itemDate = new Date(item.date)
      itemDate.setHours(0, 0, 0, 0)
      return itemDate >= today
    })
  // 合并同一天
  const map = new Map()
  validList.forEach(item => {
    if (!map.has(item.date)) {
      map.set(item.date, { date: item.date, time_slots: [...item.time_slots] })
    } else {
      // 合并并去重
      const old = map.get(item.date)
      old.time_slots = Array.from(new Set([...old.time_slots, ...item.time_slots]))
    }
  })
  // 排序
  return Array.from(map.values()).sort((a, b) => new Date(a.date) - new Date(b.date))
})

onMounted(() => {
  getCounselorInfo()
  getCounselorFreeTime()
  window.scrollTo(0, 0)
})
</script>

<style scoped>
.counselor-detail {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: white;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
  margin-right: 16px;
}

.title {
  font-size: 16px;
  font-weight: 500;
}

.content {
  padding: 16px;
}

.info-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.avatar-container {
  margin-right: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.info-content {
  flex: 1;
}

.name {
  font-size: 20px;
  font-weight: 500;
  margin: 0 0 8px 0;
  color: #333;
}

.introduction {
  font-size: 14px;
  color: #666;
  margin: 0;
  line-height: 1.5;
}

.free-time-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 16px 0;
  color: #333;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

.time-item {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.time-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.date {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.time-slots {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.time-slot {
  font-size: 12px;
}
</style>
